var express = require('express');
var request = require('request');
var $ = require('cheerio');
var RSS = require('rss');
var Q = require('q');

var app = express();

app.get('/rss/index.xml', function (req, res) {
  var options = {
    uri: 'http://diantai.ifeng.com/index.php/home/getProgramItemList?fid=1&pid=77',
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36',
      'Referer': 'http://diantai.ifeng.com/',
      'DNT': 1,
      'Host': 'diantai.ifeng.com',
      'X-Requested-With': 'XMLHttpRequest',
      'Cookie': 'ds=-854cde7cd.145170b5ad8.0.0b154cd6; samemappingcookie=m; userid=1385952663152_rtj7y3416; py_map=1; Q37_sid=8nugh1; Q37_visitedfid=160; prov=cn010; city=010; weather_city=bj; region_ip=119.57.177.x; region_ver=1.1; vjlast=1396250991.1413255913.21; userkey=af2a35f182436f5ee89c7a611ef83305'
      }
    };

  var feed = new RSS({
    title: 'title',
    description: 'description',
    feed_url: 'http://example.com/rss.xml',
    site_url: 'http://example.com',
    image_url: 'http://example.com/icon.png',
    docs: 'http://example.com/rss/docs.html',
    managingEditor: 'Dylan Greene',
    webMaster: 'Dylan Greene',
    copyright: '2013 Dylan Greene',
    language: 'en',
    categories: ['Category 1','Category 2','Category 3'],
    pubDate: 'May 20, 2012 04:00:00 GMT',
    ttl: '60'
  });

  request(options, function (error, response, body) {
    if (error) {
      return res.send('');
    }

    try {
      var data = JSON.parse(body);
      var pid = data.pfind.pid;
      var fid = data.pfind.fid;
      var totalCount = data.totalCount;
      var list = data.data;

      var dfds = [];

      list.forEach(function (item, i) {
        var getPath = function (item) {
          var dfd = Q.defer();
          var podcast = {
            id: item.rid,
            title: item.rtle,
            duration: item.rdur,
            time: item.rutime
          };

          options.uri = 'http://diantai.ifeng.com/index.php/audio/GetAudioFind?fid=1&rid=' + item.rid + '&pid=77';

          request(options, function (error, response, body) {
            if (error) {
              console.log(error);
              dfd.resolve({});
            }

            try {
              var file = JSON.parse(body);

              podcast.filepath = file.filepath;

              dfd.resolve(podcast);
            } catch (e) {
            }
          });

          return dfd.promise;
        };

        dfds.push(getPath(item));
      });

      Q.all(dfds).then(function (result) {
        result.forEach(function (item, i) {
          feed.item({
            title:  item.title,
            description: 'use this for the content. It can include html.',
            url: item.filepath, // link to the item
            date: item.time // any format that js Date can parse.
          });
        });

        var xml = feed.xml();

        xml = xml.replace('rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"', 'rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"');

        res.set('Content-Type', 'text/xml; charset=utf-8');
        res.send(xml);
      });
    } catch (e) {
      console.error(e);
    }
  });
});

var server = app.listen(4000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('app listening at http://%s:%s', host, port);
});
